package com.lenovo.smarttraffic.ui.fragment.DataAnalysisFragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.gson.Gson;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.bean.DataAnalysis.ErrorCarMessageInfo;
import com.lenovo.smarttraffic.bean.DataAnalysis.ErrorCodeInfo;
import com.lenovo.smarttraffic.bean.DataAnalysis.RemarksCodeInfo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class SevenFragment extends Fragment {


    private View view;
    private List<ErrorCarMessageInfo.ROWS_DETAIL> errorList;
    private List<ErrorCodeInfo.ROWS_DETAIL> codeList;
    private List<String> list = new ArrayList<String>();
    private Iterator iterator;
    private WebView webView;

    public SevenFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_seven, container, false);
        //初始化Webview
        webView = view.findViewById(R.id.data_analysis_webview7);
        webView.loadUrl("file:///android_asset/DataAnalysis/SevenFragment.html");
        webView.setWebViewClient(new WebViewClient());
        webView.getSettings().setJavaScriptEnabled(true);
        //数据请求
        sendErrorCarData();
        return view;
    }

    //请求违法车辆信息
    public void sendErrorCarData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = RequestBody.create(MediaType.parse("app/json"),
                            "{\"UserName\":\"user1\"}");
                    Request request = new Request.Builder()
                            .url("http://192.168.1.102:8088/transportservice/action/GetAllCarPeccancy.do")
                            .post(requestBody)
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    //数据解析
                    parseErrorCarData(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    public void parseErrorCarData(String jsonData){
        Gson gson = new Gson();
        ErrorCarMessageInfo errorInfo = gson.fromJson(jsonData, ErrorCarMessageInfo.class);
        errorList = new ArrayList<>();
        errorList.addAll(errorInfo.getROWS_DETAIL());
        //请求违章代码数据
        sendErrorCodeData();
    }

    //请求违章代码数据
    public void sendErrorCodeData() {
        try {
            OkHttpClient client = new OkHttpClient();
            RequestBody requestBody = RequestBody.create(MediaType.parse("app/json"),
                    "{\"UserName\":\"user1\"}");
            Request request = new Request.Builder()
                    .url("http://192.168.1.102:8088/transportservice/action/GetPeccancyType.do")
                    .post(requestBody)
                    .build();
            Response response = client.newCall(request).execute();
            String responseData = response.body().string();
            //解析数据
            parseErrorCodeData(responseData);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void parseErrorCodeData(String jsonData) {
        Gson gson = new Gson();
        ErrorCodeInfo codeInfo = gson.fromJson(jsonData, ErrorCodeInfo.class);
        codeList = new ArrayList<>();
        codeList.addAll(codeInfo.getROWS_DETAIL());
        //违章备注去重
        Set<String> set = new HashSet<>();
        for (int i = 0; i < codeList.size(); i++){
            set.add(codeList.get(i).getPremarks());
        }
        iterator = set.iterator();
        while (iterator.hasNext()){
            list.add((String) iterator.next());
        }
        //遍历数据 匹配违法车辆与违法代码
        List<String> remarksDataList = new ArrayList<>();  //存储所有的违章车辆的备注
        for (int i = 0; i < errorList.size(); i++) {
            for (int j = 0; j < codeList.size(); j++) {
                if ((errorList.get(i).getPcode()).equals(codeList.get(j).getPcode())) {
                    remarksDataList.add(codeList.get(j).getPremarks());
                }
            }
        }
        //存储个数的数组
        int[] remarksNum = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < remarksDataList.size(); j++) {
                if ((list.get(i).equals(remarksDataList.get(j)))) {
                    remarksNum[i]++;
                }
            }
        }

        //通过个数给个数和list集合排序
        for (int i = 0; i < remarksNum.length - 1; i++) {
            for (int j = i+1; j < remarksNum.length; j++) {
                if (remarksNum[i] < remarksNum[j]){
                    //数组互换
                    int tem = remarksNum[i];
                    remarksNum[i] = remarksNum[j];
                    remarksNum[j] = tem;
                    //集合互换
                    list.add(i, list.get(j));
                    list.add(j+1, list.get(i+1));
                    list.remove(i+1);
                    list.remove(j+1);
                }
            }
        }
        //遍历出10个集合数组对象和数字存在两个数组中
        int[] numData = new int[10];
        String[] codeData = new String[10];
        for (int i =0; i < 10; i++) {
            numData[i] = remarksNum[i];
            codeData[i] = list.get(i);
        }

        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl("javascript:getData(\""+ Arrays.toString(numData)+"\", \""+Arrays.toString(codeData)+"\")");
            }
        });

    }

}
